package com.yoshino.book.controller;

import com.google.gson.Gson;
import com.yoshino.book.pojo.Cart;
import com.yoshino.book.pojo.OrderBean;
import com.yoshino.book.pojo.User;
import com.yoshino.book.service.CartItemService;
import com.yoshino.book.service.OrderService;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class OrderController {

    private OrderService orderService;
    private CartItemService cartItemService;

    public String index(HttpSession session){
        User user = (User)session.getAttribute("currUser");

        List<OrderBean> orderList = orderService.getOrderList(user);
        user.setOrderList(orderList);
        session.setAttribute("currUser",user);
        return "order/order";
    }

    //结账
    public String checkout(HttpSession session){
        User user = (User)session.getAttribute("currUser");
        if (user.getCart().getTotalMoney() == 0){
            return "redirect:page.do?operate=page&page=cart/cart";
        }
        OrderBean orderBean = new OrderBean();
        Date now = new Date();
        int year = now.getYear();
        int month = now.getMonth();
        int day = now.getDate();
        int hours = now.getHours();
        int minutes = now.getMinutes();
        int seconds = now.getSeconds();
        orderBean.setOrderNo(UUID.randomUUID().toString() + year + month + day + hours + minutes + seconds);
        orderBean.setOrderDate(now);
        orderBean.setOrderUser(user);
        orderBean.setOrderMoney(user.getCart().getTotalMoney());
        orderBean.setOrderStatus(0);

        orderService.addOrderBean(orderBean);

        if (user != null){
            Cart cart = cartItemService.getCart(user);
            user.setCart(cart);

            session.setAttribute("currUser", user);
            return "redirect:book.do";
        }
        return "index";
    }

    //查看订单列表
    public String getOrderList(HttpSession session){
        User user = (User)session.getAttribute("currUser");

        List<OrderBean> orderList = orderService.getOrderList(user);
        user.setOrderList(orderList);
        session.setAttribute("currUser",user);

        return "order/order";
    }

    //修改订单状态（用户
    public String changeStatus(HttpSession session,String orderNo){
        orderService.changeStatus(orderNo,2);
        User user = (User)session.getAttribute("currUser");
        List<OrderBean> orderList = orderService.getOrderList(user);
        user.setOrderList(orderList);
        session.setAttribute("currUser",user);

        return "order/order";
    }

    //查看订单详细信息
    public String detailMess(Integer id){
        OrderBean orderBean = orderService.getOrderBean(id);

        Gson gson = new Gson();
        String json = gson.toJson(orderBean);
        return "json:" + json;
    }
}
